package structure.array;

import java.util.Arrays;

public class LeetCode_1968 {

    public static void main(String[] args) {
        int[] ints = {1, 2, 3, 4, 5};
        int[] ints1 = rearrangeArray(ints);
        for (int i : ints1) {
            System.out.print(i + "\t");
        }
    }

    public static int[] rearrangeArray(int[] nums) {
        boolean flag = true;
        for (int i = 1; i < nums.length - 1; i++) {
            if (nums[i] == (nums[i + 1] + nums[i - 1]) / 2) {
                flag = false;
            }
        }
        if (flag) {
            return nums;
        }

        Arrays.sort(nums);

        int left = 1, right = nums.length - 2, mid = left + (right - left) / 2;
        while (left < right) {
            while (left < right && nums[left] != (nums[left + 1] + nums[left - 1]) / 2) {
                left++;
            }

            while (left < right && nums[right] == (nums[right + 1] + nums[right - 1]) / 2) {
                right++;
            }
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left += 2;
            right -= 2;
        }

        return nums;
    }
}
